<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\NormalException;
use app\common\logic\TickCodeLogic;
use app\common\model\tick\TickCode;
use Endroid\QrCode\QrCode;
use fast\FastQrcode;
use fast\Ip;
use Linqiao\Addtran\IpRegion;
use QL\QueryList;
use think\Cache;
use think\Db;
use think\Env;
use top\test\Hello;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


//https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx?type=1&brandid=33&v=1
//https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx?type=2&seriesid=79&format=json&v=1

    /**
     * 插入品牌
     * */
    public function insert_brand(){
        $html = file_get_contents('D:\phpstudy_pro\www\promotion\public\files\brand.html');
        $data = QueryList::html($html)
            ->rules([
                'name'=>array('a','text'),
                'id'=>array('a','href')
            ])
            ->range('.item')
            ->query()->getData();
        foreach ($data->all() as $item){
            Db::name('car_brand')->insert($item);
        }

    }


    /**
     * 扫码
     *
     */
    public function scanQrCode()
    {
        $code = $this->request->param('code');
        $is_jump2 = $this->request->param('is_jump2',0);

        //二跳码
        if ($is_jump2) {
            $code = \app\common\model\tick\TickCode::where('code', $code)->value('code_jump2');
        }
        $res = (new TickCodeLogic)->scanCode($code);

        $this->success('请求成功', $res);
    }


    /**
     * 同步Qrcode
     * */
    public function syncQrcode()
    {
        $id = $this->request->param('id');
        $code_info = \app\common\model\tick\TickCode::find($id);
        $save_path = "/qrcode/{$code_info->code}.png";
        $url = $this->request->domain() . "/scan.html?code={$code_info->code}";

        try {
            $res = FastQrcode::build($url, './' . $save_path);
        } catch (NormalException $e) {
            $this->error($e->getMessage());
        }
        $code_info->qrcode_url = $this->request->domain().$save_path;
        $code_info->save();
        $this->success('', $res);
    }


}
